/*
 * Copyright (c) 2006-2009, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.livejournal;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JTextField;

import org.panteleyev.ljapi.LJAccount;
import org.panteleyev.ljapi.LJFriend;
import org.panteleyev.ljapi.LJProperties;
import org.panteleyev.swing.BasicDialog;
import org.panteleyev.swing.OkCancelButtonPanel;
import org.panteleyev.swing.SwingFactory;


public class AdvancedUserReferenceDialog extends BasicDialog<JFrame> {
    private final LJAccount account;

    private JButton     userMenuButton;
    private JTextField  usernameEdit;
    private JCheckBox   communityCheck;
    private JTextField  userTextEdit;
    private JCheckBox   userIconCheck;

    /** Creates new form AdvancedUserReferenceDialog */
    public AdvancedUserReferenceDialog(LJEditorFrame parent, LJAccount account) {
        super(parent);
        this.account = account;
        initComponents();
    }

    private void initComponents() {
        setTitle(L10N.USER_REF_DIALOG_TITLE.s());
        setHideOnClose();
        setResizable(true);

        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        getContentPane().add(SwingFactory.createPanel(BorderFactory.createTitledBorder(L10N.USER_REF_DIALOG_USERNAME_LABEL.s()), SwingFactory.LAYOUT.BOX_X,
            usernameEdit = new JTextField(15),
            Box.createHorizontalStrut(3),
            userMenuButton = new JButton("..."),
            Box.createHorizontalStrut(3),
            communityCheck = new JCheckBox(L10N.USER_REF_DIALOG_COMMUNITY_CHECKBOX.s()),
            Box.createHorizontalGlue()
        ));

        LJProperties props = account.getProperties();
        boolean b = props.getExtendedLJUser().length() != 0;

        getContentPane().add(SwingFactory.createPanel(BorderFactory.createTitledBorder(L10N.USER_REF_DIALOG_LINK_TEXT_LABEL.s()), SwingFactory.LAYOUT.BOX_X,
            userTextEdit = new JTextField(15),
            (b)? null : Box.createHorizontalStrut(3),
            (b)? null : (userIconCheck = new JCheckBox(L10N.USER_REF_DIALOG_ICON_CHECKBOX.s())),
            Box.createHorizontalGlue()
        ));

        getContentPane().add(new OkCancelButtonPanel(this));

        userMenuButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showUserMenu();
            }
        });
        userMenuButton.setFocusable(false);

        pack();
    }

    public String getReference() {
        String userName = usernameEdit.getText();
        String userText = userTextEdit.getText();

        if (userText.length() == 0) {
            userText = userName;
        }

        LJProperties props = account.getProperties();

        String ljUserExtended = props.getExtendedLJUser();
        if (ljUserExtended.length() != 0) {
            return String.format(ljUserExtended, userName, userText);
        } else {
            StringBuilder b = new StringBuilder();
            if (userIconCheck.isSelected()) {
                b.append("<a href=\"");
                b.append(props.getUserInfoURL(userName));
                b.append("\"><img height=\"17\" border=\"0\" src=\"");
                if (communityCheck.isSelected()) {
                    b.append(props.getCommInfoPictURL());
                } else {
                    b.append(props.getUserInfoPictURL());
                }
                b.append("\" alt=\"");
                b.append(userName);
                b.append("\" align=\"absmiddle\" width=\"17\"></a>");
            }
            b.append("<a style=\"FONT-WEIGHT: 800\" href=\"");
            b.append(props.getUsersURL());
            b.append(userName);
            b.append("/\">");
            b.append(userText);
            b.append("</a>");

            return b.toString();
        }
    }

    public void userMenuItemSelected(String userName) {
        LJFriend f = account.getFriend(userName);
        if (f != null) {
            this.usernameEdit.setText(userName);
            this.userTextEdit.setText(f.getFullName());
        }
    }

    private void showUserMenu() {
        LJEditorFrame frame = (LJEditorFrame)getParent();
        JMenu menu = (communityCheck.isSelected())? frame.getCommunitiesMenu() : frame.getFriendsMenu();
        int x = this.userMenuButton.getX() + userMenuButton.getWidth();
        int y = this.userMenuButton.getY();
        menu.getPopupMenu().show(this.userMenuButton.getParent(), x, y);
    }

}
